from django.http import HttpResponse
from ...models.configs import Configs

import json


def config_get(request):
    key = request.GET.get('key')
    try:
        con_obj = Configs.objects.get(marker=key)
    except:
        res_mes = {
            "code": 1,
            "message": "获取系统配置失败！"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    
    res_mes = {
        "code": 0,
        "data": con_obj.config_json
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def config_update(request):
    '''
    update
    post
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        update_config_json = json_obj['config']

        try:
            Configs.objects.filter(marker=json_obj['key']).update(config_json=update_config_json)
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": "更新数据失败！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        chatconfigs_instance = Configs.objects.filter(marker=json_obj['key']).values(
            "id",
            "marker",
            "config_json",
        )

        res_mes = {
            "code": 0,
            "data": {
                "Id": chatconfigs_instance[0]['id'],
                "Key": chatconfigs_instance[0]['marker'],
                "Config": chatconfigs_instance[0]['config_json'],
            }
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

